using System;
using Core;
using UnityEngine;

namespace g_gongjianta
{
    public class LairMainComponent : UnitComponent<Lair>, IUpdate
    {
        private float elapsedTime;
        private int count;
        private Action funcPointer;
        private TblDungeon.LairConf lairConf;

        public override void Awake()
        {
            base.Awake();

            lairConf = Unit.Conf;
            elapsedTime = 0;
            count = 0;
            funcPointer = DelayFunc;
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        public void Update()
        {
            elapsedTime += Time.deltaTime;
            funcPointer?.Invoke();
        }

        private void DelayFunc()
        {
            if (elapsedTime >= lairConf.DelayTime)
            {
                elapsedTime -= lairConf.DelayTime;
                funcPointer = MarchFunc;
                G.Factory.Create<Monster, int, Vector2>(lairConf.MonsterID, lairConf.Pos);
                count++;
            }
        }

        private void MarchFunc()
        {
            if (lairConf.Count >= 0 && count >= lairConf.Count)
            {
                funcPointer = null;
                Unit.Dispose();
                return;
            }

            if (elapsedTime >= lairConf.Interval)
            {
                elapsedTime -= lairConf.Interval;
                G.Factory.Create<Monster, int, Vector2>(lairConf.MonsterID, lairConf.Pos);
                count++;
            }
        }
    }
}